import { getRouters } from '~@/api/common/menu'
import type { UserInfo } from '~@/api/common/user'
import { getUserInfoApi, logoutUser } from '~@/api/common/user'
import type { MenuData } from '~@/layouts/basic-layout/typing'
import { rootRoute } from '~@/router/constant'
import { generateFlatRoutes, generateRoutes, generateTreeRoutes } from '~@/router/generate-route'
import { DYNAMIC_LOAD_WAY, DynamicLoadEnum } from '~@/utils/constant'
import type { AddType } from '~/api/types.ts'

export const useUserStore = defineStore('user', () => {
  const routerData = shallowRef()
  const menuData = shallowRef<MenuData>([])
  const allMenuList = shallowRef<string[]>([])
  const userInfo = shallowRef<UserInfo>()
  const token = useAuthorization()
  const avatar = computed(() => userInfo.value?.avatar)
  const routerPath = ref<string | undefined>('')
  const nickname = computed(() => userInfo.value?.nickName ?? userInfo.value?.username)
  const roles = ref<Array<string>>([])
  const permissions = ref<Array<string>>([])
  const selectMansionId = ref<string | number>('')
  const addType = ref< number>(0)
  const addCount = ref< number>(0)

  const getMenuRoutes = async () => {
    const { data } = await getRouters()
    console.log('menu==========', data)
    return generateTreeRoutes(data)
  }

  const generateDynamicRoutes = async () => {
    const dynamicLoadWay = DYNAMIC_LOAD_WAY === DynamicLoadEnum.BACKEND ? getMenuRoutes : generateRoutes
    const { menuData: treeMenuData, routeData, allMenuPath } = await dynamicLoadWay()

    menuData.value = treeMenuData
    allMenuList.value = allMenuPath
    routerData.value = {
      ...rootRoute,
      children: generateFlatRoutes(routeData),
    }
    console.log('routerData=======', routerData.value, routeData, menuData)
    return routerData.value
  }

  // 获取用户信息
  const getUserInfo = async () => {
    // 获取用户信息
    const { data } = await getUserInfoApi()
    console.log('data=======', data)
    userInfo.value = data.user
    routerPath.value = data.user.routerPath
    if (data.roles && data.roles.length > 0) {
      // 验证返回的roles是否是一个非空数组
      roles.value = data.roles
      permissions.value = data.permissions
    }
    else {
      roles.value = ['ROLE_DEFAULT']
    }
  }

  const setAddCount = (type: AddType) => {
    addType.value = type
    addCount.value = addCount.value + 1
    console.log('改变 account=========')
  }

  const logout = async () => {
    // 退出登录
    // 1. 清空用户信息
    try {
      await logoutUser()
    }
    finally {
      token.value = null
      userInfo.value = undefined
      routerData.value = undefined
      menuData.value = []
    }
  }

  const setSelectMansionGroupId = (mansionGroupId: string | number) => {
    selectMansionId.value = mansionGroupId
  }

  const setRouterPath = (routerPathNew: string | undefined) => {
    routerPath.value = routerPathNew
  }

  const hasPermission = (value: Array<string>) => {
    if (value && Array.isArray(value) && value.length > 0) {
      const hasPermission = permissions.value.some((permi) => {
        return permi === '*:*:*' || value.includes(permi)
      })
      return hasPermission
    }
    else {
      console.error('check perms! Like v-has-permi="[\'system:user:add\',\'system:user:edit\']"')
    }
    return false
  }

  return {
    userInfo,
    roles,
    permissions,
    getUserInfo,
    setRouterPath,
    selectMansionId,
    logout,
    addType,
    addCount,
    setAddCount,
    routerData,
    menuData,
    allMenuList,
    generateDynamicRoutes,
    setSelectMansionGroupId,
    avatar,
    routerPath,
    hasPermission,
    nickname,
  }
})
